package org.pasta.web.controller.login;

import java.util.ArrayList;
import java.util.List;

import org.pasta.data.PopupMessage;
import org.pasta.data.User;
import org.pasta.web.controller.POSController;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

public class LoginController extends POSController {
	
	ModelAndView loginPage = new ModelAndView("login");
	ModelAndView mainPage = new ModelAndView("main");
	
	/* Define Field ID In Page*/
	private String USER_ID_FIELD = "userId";
	private String PWD_FIELD = "pwd";
	/* End Define Field ID In Page*/

	protected ModelAndView process() {
		User loginUser = null;
		
		String userId = getParameter(USER_ID_FIELD);
		String pwd = getParameter(PWD_FIELD);
		
		if(session.getAttribute(this.USER_SESSION)!= null)
			loginUser = (User)session.getAttribute(this.USER_SESSION);
		
		if(!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(pwd)){
			// Authentication Here 
			if(login(userId,pwd)){
				loginUser = new User();
				loginUser.setCitizenId("311-0200680-57-2");
				loginUser.setName("Pasuwat");
				loginUser.setLastName("Wang-arrayagul");
			}
			else{
				PopupMessage message = new PopupMessage();
				message.setType(this.ERROR_MSG_TYPE);
				message.setMessage("Invalid User Name or Password!");
				request.setAttribute(MESSAGE, message);
			}
		}
		
		if(loginUser ==null)
			return loginPage;
		
		session.setAttribute(this.USER_SESSION, loginUser);
		return mainPage;
	}
	
	private List<String> userIds = new ArrayList<String>();
	private List<String> passwords = new ArrayList<String>();
	
	{
		// Initial Sample User & Password
		userIds.add("pasuwatw");
		userIds.add("sukritta");
		userIds.add("chai");
		userIds.add("ngek");
		
		passwords.add("welcome1");
		passwords.add("mininara");
		passwords.add("welcome2");
		passwords.add("mininara1");
	}

	private boolean login(String userId, String pwd) {
		int idx = 0;
		for(String uid : userIds){
			if(uid.equals(userId)){
				return passwords.get(idx).equals(pwd);
			}
			idx++;
		}
		
		return false;
	}

}
